﻿$kk = {}; kk = $kk;

//配置
$kk.config = {
    loadingDelay: 800, //loading加载的延迟时间,800毫秒
    stopDrawing: false,//是否停止渲染选项
}

//原始数据
$kk.data = {
    
};

$kk.error = function (message) {
    $kk.popup(message, "error");
};

//弹出层
$kk.popup = function (message, delay, type) {
    var config = $kk.parseArgs(delay, type);
    config = $kk.mergePlainObject({
        message: message,
        delay: config.Number[0],
        type: config.String[0],
    }, config.Json[0]);

    var panel = $("div[alert-panel]");
    if (panel.length == 0) {
        panel = $("<div alert-panel style='position:fixed;z-index:1000;top:0;left:0;width:100%;text-align: center;' />");
        $("body").prepend(panel);
    }
    var $div = $("<div onselectstart='return false' class='alert alert-dismissible'/>")

    $div.click(function () { $(this).slideUp(function () { $(this).remove(); }); });
    config.type = {
        warning: "warning",
        warn: "warning",
        danger: "danger",
        error: "danger",
        err: "danger",
        success: "success",
        ok: "success",
        info: "info",
    }[config.type] || "info";
    $div.addClass("alert-" + config.type);
    $div.css({ padding: "7px 10px 5px", "margin-bottom": "5px", cursor: "pointer" });
    $div.append(config.message).hide();
    panel.prepend($div);
    $div.slideDown();
    if (config.delay > 0 || (config.type == "success" && config.delay == null)) {
        setTimeout(function () { $div.slideUp(function () { $(this).remove(); }); }, config.delay || 1500);
    }
    return $div;
};

//触发事件
$kk.fireEvent = function (jq, event) {
    $(jq).each(function () {
        if (this.isFireEvent) {
            return;
        }
        this.isFireEvent = true;
        $(this).trigger(event);
        delete this.isFireEvent;
    });
};

//获取参数
$kk.getElementArgs = function (jq, option) {
    try {
        var args = $(jq).eq(0).attr("kk-data");
        if (args) {
            args = eval("(" + args + ")");
        }
        if ($.isPlainObject(args)) {
            return args;
        }
        if (option) {
            args = args || {};
            for (var i in option) {
                if (i in args == false) {
                    agrs[i] = option[i];
                }
            }
        }
        return args || {};
    } catch (e) {
        return option || {};
    }
};

//克隆对象
$kk.clonePlainObject = function (obj) {
    return $.extend({}, obj);
};

//合并对象,数值以obj1为主
$kk.mergePlainObject = function (obj1, obj2) {
    var args = $.merge([true, {}], arguments)
    return $.extend.apply($, args);
}

//分析方法参数
$kk.parseArgs = function () {
    var args = {
        Number: [],
        String: [],
        Boolean: [],
        Array: [],
        Json: [],
        DateTime: [],
        Object: [],
        Function: [],
        JQuery: [],
        Dom: []
    };
    for (var i = 0; i < arguments.length; i++) {
        var v = arguments[i];
        if (v !== null && v !== undefined) {
            if (v.constructor === Number) {
                args.Number.push(v);
            } else if (v.constructor === String) {
                args.String.push(v);
            } else if (v.constructor === Boolean) {
                args.Boolean.push(v);
            } else if (v.constructor === Date) {
                args.DateTime.push(v);
            } else if (v.constructor === Array) {
                args.Array.push(v);
            } else if (v.constructor === Function) {
                args.Function.push(v);
            } else if (v instanceof jQuery) {
                args.JQuery.push(v);
            } else if (v instanceof HTMLElement) {
                args.Dom.push(v);
            } else if ($.isPlainObject(v)) {
                args.Json.push(v);
            }
        }
    }
    return args;
};

//动态加载文件
$kk.include = function (file) {
    var option = $kk.parseArgs.apply(window, arguments);
    var files = option.Array[0] || option.String;
    var callback;
    var length = files.length;
    var ok = 0;
    if (option.Function.length > 0) {
        callback = function () {
            ok++;
            if (ok == length) {
                option.Function[0]();
            }
        };
    }

    for (var i = 0; i < length; i++) {
        var name = $.trim(files[i]);
        var att = name.split('.');
        var ext = att[att.length - 1].toLowerCase();
        if (ext == "css") {
            $("<link />").attr({ type: "text/css", rel: "stylesheet", "href": name }).appendTo("head");
            ok++;
        } else {
            $.getScript(name, callback);
        }
    }
};

//是否处于loading状态
$kk.isLoading = false;

//显示loading框
$kk.loading = function () {
    return true;
};

//关闭loading框
$kk.unLoading = function () {
    return true;
}

//填充数据
$kk.fillTable = function (selector, data, setData) {
    var table = $(selector)
    if (table.length != 1 || table.is("table") == false) {
        throw Error("绑定对象太多或不是table");
    }

    var func = null;
    if (setData && setData.constructor === Function) {
        func = setData;
    }

    var template = table.data("grid-template");
    if (!template) {
        template = table.find("tr[template]");
        if (template.length == 0) {
            template = table.find("tbody tr:first");
        }
        table.data("grid-template", $("<div />").append(template.attr("data-row", "").show()).html());
        template.remove();
        template = table.data("grid-template");
    } else {
        table.find("[data-row]").remove();
    }
    if (!data || data.constructor !== Array) {
        return;
    }

    var tbody = table.find("tbody");
    for (var i in data) {
        var it = data[i];
        var html = template.replace(/\{[^{}]+\}/g, function (a) {
            var name = a.slice(1, -1);
            if (func) {
                var value = func(it, name);
                if (value !== undefined) {
                    return $kk.IsNull(value);
                }
            }
            return $kk.encodeHTML(it[name]);
        });
        tbody.append(html);
    }
};

//填充数据集合
$kk.fillList = function (selector, data, setData) {
    var list = $(selector)
    if (list.length != 1) {
        throw Error("绑定对象太多");
    }

    var func = null;
    if (setData && setData.constructor === Function) {
        func = setData;
    }

    var template = list.data("grid-template");
    if (!template) {
        template = list.find("[template]");
        if (template.length == 0) {
            template = list.find("> *");
        }
        list.data("grid-template", $("<div />").append(template.attr("data-item", "").show()).html());
        template.remove();
        template = list.data("grid-template");
    } else {
        list.find("[data-item]").remove();
    }
    if (!data || data.constructor !== Array) {
        return;
    }

    for (var i in data) {
        var it = data[i];
        var html = template.replace(/\{[^{}]+\}/g, function (a) {
            var name = a.slice(1, -1);
            if (func) {
                var value = func(it, name);
                if (value !== undefined) {
                    return $kk.IsNull(value);
                }
            }
            return $kk.encodeHTML(it[name]);
        });
        list.append(html);
    }
};

//填充数据2
$kk.fillData = function (selector, data, setData) {
    var panel = $(selector)
    if (panel.length == 1 && panel.is("table")) {
        $kk.fillTable(selector, data, setData);
        return;
    } else if (panel.length == 0) {
        return;
    } else if (panel.length > 1) {
        panel.each(function () {
            $kk.fillData(this, data, setData);
        });
        return;
    }
    var func = null;
    if (setData && setData.constructor === Function) {
        func = setData;
    }
    var template = panel.data("grid-template");
    if (!template) {
        template = panel.html();
        panel.data("grid-template", template);
    } else {
        panel.html('');
    }
    if (data) {
        var html = template.replace(/\{[^{}]+\}/g, function (a) {
            var name = a.slice(1, -1);
            if (func) {
                var value = func(data, name);
                if (value !== undefined) {
                    return $kk.IsNull(value);
                }
            }
            return $kk.encodeHTML(data[name]);
        });
        panel.html(html);
    }
};

$(document).on("change.kk_bindCheckAll", ":checkbox", function (e) {
    var flag = $(this).attr("kk_checkflag");
    if (flag) {
        function setChecked(ckb, b) {
            if (ckb.checked !== b) {
                ckb.checked = b;
                $kk.fireEvent(ckb, "change");  //触发click事件
            }
        };

        var first = flag.charAt(0);
        flag = flag.substr(1);
        if (kk.data[flag]) {
            return;
        }
        kk.data[flag] = true;
        if (first == "m") {
            var checked = $(this).prop("checked");
            $(":checkbox[kk_checkflag='s" + flag + "']").each(function () {
                setChecked(this, checked);
            });
        } else {
            setChecked(
                $(":checkbox[kk_checkflag='m" + flag + "']")[0],
                $(":checkbox[kk_checkflag='s" + flag + "']").not(":checked").length == 0
                );
        }

        delete kk.data[flag];
    }
});
//绑定全选事件
$kk.bindCheckAll = function (checkbox, checkboxs) {

    checkbox = $(checkbox);
    if (checkbox.length < 1) {
        this.error("至少需要1个元素");
        return;
    }
    checkboxs = $(checkboxs).not(checkbox);
    if (checkboxs.length < 1) {
        return;
    }
    var flag = Math.random();
    checkbox.attr("kk_checkflag", "m" + flag);
    checkboxs.attr("kk_checkflag", "s" + flag);
};

//树状函数
$kk.drawingTree = function (tds) {

    var tree = $.map(tds, function (n) {
        return parseInt($(n).attr("level"));
    });

    var createNode = function (index) {
        var curr = {
            lv: tree[index],
            icons: []
        };
        tree[index] = curr;
        if (curr.lv == 0) { //顶级菜单
            return curr;
        }

        for (var i = 0; i < (curr.lv - 1) ; i++) {
            curr.icons.push(0);
        }

        if (tree.length == index + 1) { //最后一个菜单
            curr.icons.push(2);
            return curr;
        }

        var next = tree[index + 1];
        var diff = next.lv - curr.lv;

        var copyIcons = function (count) {
            count = Math.min(count, next.icons.length);
            for (var i = 0; i < count; i++) {
                curr.icons[i] = (next.icons[i] == 0) ? 0 : 1;
            }
        }

        switch (diff) {
            case 0:
                copyIcons(curr.lv - 1);
                curr.icons.push(3);
                break;
            case 1:
                copyIcons(curr.lv - 1);
                var icon = next.icons.slice(-2, -1)[0];
                switch (icon) {
                    case 0:
                        curr.icons.push(2);
                        break;
                    case 1:
                        curr.icons.push(3);
                        break;
                    case 2:
                        curr.icons.push(1);
                        break;
                    case 3:
                        curr.icons.push(3);
                        break;
                    default:
                        break;
                }
                break;
            case -1:
                copyIcons(curr.lv - 2);
                if (next.lv > 0) {
                    curr.icons.pop();
                    curr.icons.push(1);
                }
                curr.icons.push(2);
                break;
            default:
                copyIcons(curr.lv - 1);
                curr.icons.push(2);
                break;
        }
        return curr;
    }

    for (var i = tree.length - 1; i >= 0; i--) {
        var td = $(tds[i]);
        var node = createNode(i);
        if (node.lv == 0) {
            continue;
        }
        var txt = td.html();
        td.empty();
        for (var j in node.icons) {
            switch (node.icons[j]) {
                case 0:
                    td.append('<div class="line_none fl">');
                    break;
                case 1:
                    td.append('<div class="line_conn fl">');
                    break;
                case 2:
                    td.append('<div class="line_bottom fl">');
                    break;
                case 3:
                    td.append('<div class="line_center fl">');
                    break;
                default:
                    break;
            }
        }
        td.find("div:last-child").html(txt);
    }
};

//格式化json对象或json字符串
$kk.jsonFormat = function (json) {
    var obj = json;
    if (json.constructor === String) {
        obj = JSON.parse(json);
    }

    var buffer = [];

    var space = function (c) {
        for (var i = 0; i < c; i++) {
            buffer.push("&nbsp;");
        }
    }

    var append = function (o, d) {
        if ($.isArray(o)) {
            buffer.push("[<br />");
            var b = false;
            for (var i in o) {
                if (b) {
                    buffer.push(" ,<br />");
                }
                b = true;
                space((d + 1) * 2);
                append(o[i], d + 1);
            }
            buffer.push("<br />");
            space(d * 2);
            buffer.push("]");
        } else if ($.isPlainObject(o)) {
            buffer.push("{<br />");
            var b = false;
            for (var i in o) {
                if (b) {
                    buffer.push(" ,<br />");
                }
                b = true;
                space((d + 1) * 2);
                buffer.push(JSON.stringify(i));
                buffer.push(" : ");
                append(o[i], d + 1);
            }
            buffer.push("<br />");
            space(d * 2);
            buffer.push("}");
        } else {
            buffer.push(JSON.stringify(o));
        }
    }
    append(obj, 0);
    return buffer.join("");
};

//获取url参数值
$kk.queryString = function (name) {
    var rex = new RegExp("[?&]\s*" + name + "\s*=([^&$#]*)", "i");
    var r = rex.exec(location.search);
    if (r && r.length == 2)
        return r[1];
}

$kk.IsNull = function (obj, defaultValue) {
    if (obj != null) {
        return obj;
    }
    if (defaultValue == null) {
        return "";
    }
    return defaultValue;
}

$kk.encodeHTML = function (data) {
    if (data == null) {
        return "";
    }
    return data.toString().replace(/[<>&" ]/g, function (m) {
        switch (m) {
            case "<":
                return "&lt;";
            case ">":
                return "&gt;";
            case "&":
                return "&amp;";
            case '"':
                return "&quot;";
            case " ":
                return "&nbsp;";
            default:
                break;
        }
    })
}

$kk._api = function (url) {
    var me = this;
    this.baseUrl = url;

    function processResult(result, success, fail) {
        if ("Code" in result && "Message" in result && "Data" in result) {
            if (result.Code == 1) {
                kk.alert(result.Message);
                return;
            }
            if (result.Code == 302) {
                kk.loading();
                window.location = result.Message;
                return;
            }
            if (result.Code == 4002 && $kk.config.login.url != null) {
                kk.loading();
                $kk.config.login.target.location = $kk.config.login.url;
                return;
            }
            if (result.Code != 0) {
                if (result.Code < 0 && fail) {
                    fail(result);
                } else {
                    kk.popup(result.Message, "err");
                }
                return;
            }
            result = result.Data;
        }
        try {
            success && success(result);
        } catch (e) {
            $kk.error("回调方法异常:" + e.message);
        }
    };


    function ajax(method, route, data, success, fail) {
        if ($.isFunction(data)) {
            if ($.isFunction(success)) {
                fail = success;
            }
            success = data;
            data = null;
        }
        data = data || {};
        data.agent = "ajax"
        $kk.loading();
        return $.ajax({
            dataType: "json",
            url: me.baseUrl + route,
            type: method,
            data: data,
            success: function (r) {
                processResult(r, success, fail);
            },
        });
    }
    this.get = function (route, data, success, fail) {
        return ajax("GET", route, data, success, fail);
    }
    this.post = function (route, data, success, fail) {
        return ajax("POST", route, data, success, fail);
    }
    this.jsonp = function (route, data, success, fail) {
        if ($.isFunction(data)) {
            if ($.isFunction(success)) {
                fail = success;
            }
            success = data;
            data = null;
        }
        data = data || {};
        data.agent = "jsonp"
        kk.loading();
        var result = $.ajax({
            dataType: "jsonp",
            url: "http://loan.test.tops001.com/" + route,
            type: "POST",
            data: data,
            success: function (result) {
                kk.unLoading();
                processResult(result, success, fail);
            },
        });
        setTimeout(function () {
            if (result.readyState == 1) {
                kk.popup("请求超时:" + me.baseUrl + route, "err");
                $kk.unLoading();
            }
        }, 10000);
    }
};
(function () {
    $kk.api = new $kk._api("");
})();
$kk.api.add = function (name, url) {
    this[name] = new $kk._api(url);
};

//其他功能
//格式化时间
var ___DateToString = Date.prototype.toString;
Date.prototype.toString = function (format) {
    if (format === undefined) {
        return ___DateToString.apply(this);
    }
    if (format === null) {
        format = "yyyy-MM-dd HH:mm:ss";
    }

    format = format.replace(/yyyy/g, this.getFullYear());
    format = format.replace(/yyy/g, this.getYear());
    format = format.replace(/yy/g, this.getFullYear().toString().slice(-2));

    if (format.indexOf('mi') >= 0) {
        format = format.replace(/mi/g, this.getMilliseconds().toString());
    }

    if (format.indexOf('M') >= 0) {
        var M = (this.getMonth() + 1).toString();
        format = format.replace(/MM/g, ("0" + M).slice(-2));
        format = format.replace(/M/g, M);
    }

    if (format.indexOf('ddd') >= 0) {
        var xq = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
        format = format.replace(/ddd/g, xq[this.getDay()]);
    }

    if (format.indexOf('d') >= 0) {
        var d = this.getDate().toString();
        format = format.replace(/dd/g, ("0" + d).slice(-2));
        format = format.replace(/d/g, d);
    }


    if (format.indexOf('h') >= 0 || format.indexOf('H') >= 0) {
        var h = this.getHours().toString();
        format = format.replace(/HH/g, ("0" + h).slice(-2));
        format = format.replace(/H/g, h);
        h = h % 12;
        format = format.replace(/hh/g, ("0" + h).slice(-2));
        format = format.replace(/h/g, h);
    }

    if (format.indexOf('m') >= 0) {
        var m = this.getMinutes().toString();
        format = format.replace(/mm/g, ("0" + m).slice(-2));
        format = format.replace(/m/g, m);
    }

    if (format.indexOf('s') >= 0) {
        var s = this.getSeconds().toString();
        format = format.replace(/ss/g, ("0" + s).slice(-2));
        format = format.replace(/s/g, m);
    }

    if (format.indexOf('f') >= 0) {
        var f = this.getMilliseconds().toString();
        format = format.replace(/fff/g, ("000" + f).slice(-3));
        format = format.replace(/ff/g, ("000" + f).slice(-3).substr(0, 2));
        format = format.replace(/f/g, ("000" + f).slice(-3).substr(0, 1));
    }
    //.getMilliseconds()

    return format;
};
Date.prototype.checkNumber = function (value) {
    if (+value !== value) {
        throw new Error("必须是数字");
    }
};

//时间加减
Date.prototype.add = function (type, value) {
    this.checkNumber(value);
    var date = new Date(this);
    switch (type) {
        case 'y':
        case 'Y':
            date.setYear(this.getYear() + value);
            break;
        case 'M':
            date.setMonths(this.getMonths() + value);
            break;
        case 'd':
        case 'D':
            date.setDate(this.getDate() + value);
            break;
        case 'h':
        case 'H':
            date.setHours(this.getHours() + value);
            break;
        case 'm':
            date.setMinutes(this.getMinutes() + value);
            break;
        case 'S':
        case 's':
            date.setSeconds(this.getSeconds() + value);
            break;
        case 'f':
            date.setMilliseconds(this.getMilliseconds() + value);
            break;
        default:
            throw Error("type只能是:y,Y,M,d,D,h,H,m,s,S,f");
    }
    return date;
};

Date.prototype.addDays = function (value) { return this.add("d", value); };
Date.prototype.addHours = function (value) { return this.add("h", value); };
Date.prototype.addMilliseconds = function (value) { return this.add("f", value); };
Date.prototype.addMinutes = function (value) { return this.add("m", value); };
Date.prototype.addMonths = function (value) { return this.add("M", value); };
Date.prototype.addSeconds = function (value) { return this.add("s", value); };
Date.prototype.addYears = function (value) { return this.add("y", value); };


//ajax全局处理
jQuery(document).ajaxStart(function () {
    $kk.loading();
});
jQuery(document).ajaxStop(function () {
    $kk.unLoading();
});
jQuery(document).ajaxError(function (event, result, ajax) {
    if (result.responseText.substr(0, 12) == "error_debug:") {
        $kk.confirm(result.responseText, "DEBUG");
    } else {
        $kk.popup("请求服务器: " + ajax.url + " 失败\n原因: " + result.state(), "err");
    }
});

$(window).on("beforeunload", function () {
    if (navigator || (/(iPhone|iPad|iPod)/i).test(navigator.userAgent) == false) { //判断safari浏览器
        kk.loading(); //页面跳转时的loading效果
    }
});

//拓展jquery方法
jQuery.prototype.attrop = function (name, value) {
    if (value) {
        this.attr(name, value);
        this.prop(name, value);
        return this;
    } else {
        return this.attr(name) || this.prop(name);
    }
}
//处理页面所有a标签
$("a:not([href]),a[href=#]").attrop("href", "javascript:void(0)");